package com.safetys.co.idaas.service;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.safetys.co.idaas.entity.Settings;
import com.safetys.co.idaas.ex.IdaasException;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @author deqing.chedq
 * @Date 2025/5/28 13:26
 * @Description
 */
@Slf4j
@ToString
public class IdaasService {

    private static IdaasService apiSixPluginsService = null;
    private Settings settings = new Settings();

    private IdaasService() {

        super();
        Setting setting = new Setting("idaasHelper.properties");
        log.info(setting.toString());

        settings.setServiceURL(setting.get("idaas.serviceURL"));
        settings.setUsername(setting.get("idaas.username"));
        settings.setPassword(setting.get("idaas.password"));
        settings.setCode(setting.get("idaas.code"));
        settings.setUuid(setting.get("idaas.uuid"));
    }

    private IdaasService(Settings settings) {

        super();
        this.settings = settings;
    }

    public Settings getSettings() {
        return settings;
    }

    public static IdaasService getInstance() {

        if (apiSixPluginsService == null) {
            apiSixPluginsService = new IdaasService();
        }
        return apiSixPluginsService;
    }

    public static IdaasService getInstance(Settings settings) {

        if (apiSixPluginsService == null) {
            apiSixPluginsService = new IdaasService(settings);
        }
        return apiSixPluginsService;
    }

    public String auth() throws IdaasException {

        log.info("call auth ...");
        String requestBody = JSONUtil.toJsonStr(settings);
        log.info(requestBody);
        HttpResponse response = HttpUtil.createRequest(Method.POST, settings.getServiceURL()).contentType(ContentType.JSON.getValue())
                .body(requestBody)
                .execute();
        log.info(response.body());
        JSONObject ret = JSONUtil.parseObj(response.body());
        log.info("status {}", response.getStatus());
        if ("200".equals(ret.get("code").toString())){
            return ret.get("token").toString();
        } else {
            return null;
        }
    }
}
